/**
 * Copyright (c) 2015-2020, ShangRao Institute of Big Data co.,LTD and/or its
 * affiliates. All rights reserved.
 */
package cn.ibdsr.human.service.impl;

import cn.ibdsr.human.config.FastdfsProperties;
import cn.ibdsr.human.service.FdfsClientService;
import com.luhuiguo.fastdfs.conn.ConnectionManager;
import com.luhuiguo.fastdfs.conn.FdfsConnectionPool;
import com.luhuiguo.fastdfs.conn.TrackerConnectionManager;
import com.luhuiguo.fastdfs.domain.StorePath;
import com.luhuiguo.fastdfs.exception.FdfsException;
import com.luhuiguo.fastdfs.service.DefaultFastFileStorageClient;
import com.luhuiguo.fastdfs.service.DefaultTrackerClient;
import com.luhuiguo.fastdfs.service.FastFileStorageClient;
import com.luhuiguo.fastdfs.service.TrackerClient;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description fastdfs 客户端实现类
 * @Version V1.0
 * @CreateDate 2018/4/10 15:50
 *
 * Date           Author               Description
 * ------------------------------------------------------
 * 2018/4/10      ZhangLin               类说明
 *
 */
@Service("fdfsClientService")
public class FdfsClientServiceImpl implements FdfsClientService {

    /**日志*/
    protected static final Logger LOGGER = LoggerFactory.getLogger(FdfsClientServiceImpl.class);

    @Autowired
    private FastdfsProperties fastdfsProperties;/**配置信息*/

    private FastFileStorageClient storageClient;

    @PostConstruct
    public void init() {
        FdfsConnectionPool pool = new FdfsConnectionPool();
        List<String> trackers = new ArrayList<>();
        trackers.add(fastdfsProperties.getTrackers());
        TrackerConnectionManager tcm = new TrackerConnectionManager(pool, trackers);
        TrackerClient trackerClient = new DefaultTrackerClient(tcm);
        ConnectionManager connectionManager = new ConnectionManager(pool);
        storageClient = new DefaultFastFileStorageClient(trackerClient, connectionManager);
    }

    @Override
    public String uploadFile(byte[] content, String extendName) {
        Validate.notNull(content, "文件内容不能为空");
        Validate.notNull(extendName, "文件扩展名不能为空");
        try {
            StorePath path = storageClient.uploadFile(content, extendName);
            return path.getFullPath();
        } catch (FdfsException e) {
            LOGGER.error( "上传文件出错, 扩展名称是 ".concat(extendName).
                    concat(", 原因是" + e.getMessage()), e);
            return null;
        }
    }

    @Override
    public void deleteFile(String filePath) {
        Validate.notNull(filePath, "文件存储路径不能为空");
        storageClient.deleteFile(filePath);
    }
}
